require("dotenv").config();
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");

const app = express();
const PORT = process.env.PORT || 3000;

// 连接到 MongoDB
mongoose
	.connect("mongodb://43.136.72.241:27017/sparrow-god", {
		useNewUrlParser: true,
		useUnifiedTopology: true,
	})
	.then(() => console.log("MongoDB Connected"))
	.catch(err => console.log(err));

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 启动服务
app.listen(PORT, () => {
	console.log(`Server running on port ${PORT}`);
});

// 登录接口 post login
const userLogin = require("./routes/login");
app.use("/login", userLogin);

// 新增用户信息 post users
const userRoutes = require("./routes/users");
app.use("/users", userRoutes);

// 记录
const listRoutes = require("./routes/record");
app.use("/record", listRoutes);

// 添加在路由之后
const { notFound, errorHandler } = require("./middleware/errorHandler");
app.use(notFound);
app.use(errorHandler);
